'use strict';

/*
 * Adaptor，添加向后台请求的函数
*/
const Adaptor = require('@cvte/easi-adaptor');
const _ = require('lodash');

module.exports = () => async function adaptor(ctx, next) {

    const config = ctx.app.config;

    const token = ctx.cookies.get('x-token', {signed: false}) || ctx.cookies.get('x-auth-token', {signed: false}) || '';

    const appCode = ctx.cookies.get('x-auth-app', {
        signed: false
    });

    const ip = ctx.headers['x-real-ip'];

    const headers = {
        'Content-Type': 'application/json',
        'xx-real-ip': ip || '',
        'x-auth-refer': config.authRefer || 'EasiNote',
        Cookie: `x-auth-token=${token};x-auth-app=${appCode || config.appCode}`,
        'x-auth-token': token,
    };

    const adaptorConfig = {
        validatiors: {},
        apis: ctx.app.apis,
        http: {
            headers: headers,
            baseURL: config.serverUrl,
            beforeRequest: function (httpConfig) {
                // 因为有多个后台服务，这里是针对直播后台服务做得特殊处理
                if(httpConfig.url.startsWith('/server/v1/web'))
                {
                    httpConfig.baseURL = config.liveServerUrl;
                }
                ctx.swLog.info('HTTP Request before', JSON.stringify(httpConfig));
            }
        },
        mock: {
            baseURL: config.mockApiUrl,
        }
    }

    const adaptor = new Adaptor(adaptorConfig);
    ctx.callAPI = adaptor.dispatch.bind(adaptor);

    await next();
}